package com.start.platform.wx;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.start.common.exceptions.StartBusException;
import com.start.platform.core.StartBasePlatformService;
import com.start.platform.core.entity.StartPlatformConfigEntity;
import com.start.platform.core.entity.StartPlatformFans;
import com.start.platform.core.service.StartPlatformFansService;
import com.start.platform.core.vo.StartPlatformFansDetail;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Service
public class WeiXinMiniAppPlatformService implements StartBasePlatformService<WxMaService> {

    private final static Map<String, WxMaService> wxMaServiceMap = new HashMap<>();

    @Autowired
    private StartPlatformFansService platformFansService;


    private WxMaConfig createWxMaConfigStorage(StartPlatformConfigEntity entity) {
        WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        config.setAppid(entity.getAppId());
        config.setSecret(entity.getSecret());
        config.setAesKey(entity.getAesKey());
        config.setToken(entity.getToken());
        return config;
    }

    /**
     * 平台类型
     *
     * @return
     */
    @Override
    public String getPlatformType() {
        return SystemConstant.PlatformTypes.WX.MINI_APP;
    }

    @Override
    public String getPlatformTypeLabel() {
        return "微信小程序";
    }

    /**
     * 添加配置
     *
     * @param config
     */
    @Override
    public void add(StartPlatformConfigEntity config) {
        if (wxMaServiceMap.containsKey(config.getAppId())) {
            return;
        }
        WxMaService wxMaService = new WxMaServiceImpl();
        wxMaService.setWxMaConfig(createWxMaConfigStorage(config));
        wxMaServiceMap.put(config.getAppId(), wxMaService);
    }

    @Override
    public void remove(String appId) {
        if (!wxMaServiceMap.containsKey(appId)) {
            return;
        }
        wxMaServiceMap.remove(appId);
    }

    /**
     * 修改配置
     *
     * @param appId
     * @param config
     */
    @Override
    public void updateByAppId(String appId, StartPlatformConfigEntity config) {
        if (!wxMaServiceMap.containsKey(appId)) {
            return;
        }
        remove(config.getAppId());
        add(config);
    }

    /**
     * 是否存在AppId
     *
     * @param appId
     * @return
     */
    @Override
    public boolean hasAppId(String appId) {
        return wxMaServiceMap.containsKey(appId);
    }

    /**
     * 获取平台服务
     *
     * @param appId
     * @return
     */
    @Override
    public WxMaService getPlatformService(String appId) {
        if (!wxMaServiceMap.containsKey(appId)) {
            return null;
        }
        return wxMaServiceMap.get(appId);
    }


    private WxMaUserInfo getUserInfo(String appId, String code, JSONObject prop) {
        String signature = prop.getString("signature");
        String rawData = prop.getString("rawData");
        String encryptedData = prop.getString("encryptedData");
        String iv = prop.getString("iv");
        WxMaService service = getPlatformService(appId);
        WxMaJscode2SessionResult session = null;
        try {
            session = service.getUserService().getSessionInfo(code);
        } catch (WxErrorException e) {
            e.printStackTrace();
            throw new StartBusException("用户登录失败");
        }
        String sessionKey = session.getSessionKey();
        if (!service.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            throw new StartBusException("用户信息校验失败");
        }
        return service.getUserService().getUserInfo(sessionKey, encryptedData, iv);
    }

    @Override
    public StartPlatformFansDetail getUserInfoByPlatformCode(String appId, String code, JSONObject prop) {
        WxMaUserInfo userInfo = getUserInfo(appId, code, prop);
        StartPlatformFans fans = platformFansService.getFansByOpenId(SystemConstant.PlatformTypes.WX.MINI_APP, appId, userInfo.getOpenId());
        StartPlatformFansDetail detail = null;
        if (fans == null) {
            detail = new StartPlatformFansDetail();
            detail.setNewUser(true);
            detail.setPlatformOpenId(userInfo.getOpenId());
            detail.setPlatformType(SystemConstant.PlatformTypes.WX.MINI_APP);
            detail.setPlatformAppId(appId);
        } else {
            detail = StartPlatformFansDetail.create(fans);
        }
        detail.setPlatformFansInfo(JSONObject.from(userInfo));
        final JSONObject avatar = new JSONObject();
        avatar.put("label", "");
        avatar.put("value", userInfo.getAvatarUrl());
        JSONArray array = new JSONArray();
        array.add(avatar);
        detail.setAvatar(array);
        detail.setNickName(userInfo.getNickName());
        detail.setSex(getSex(userInfo));
        detail.setPlatformLastLoginTime(LocalDateTime.now());
        platformFansService.saveOrUpdate(detail);
        return detail;
    }


    private Integer getSex(WxMaUserInfo wxMpUser) {
        if (StringUtils.isEmpty(wxMpUser.getGender())) return 0;
        if (wxMpUser.getGender().equals("男")) return 1;
        if (wxMpUser.getGender().equals("女")) return 2;
        try {
            return Integer.parseInt(wxMpUser.getGender());
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 平台验证token
     *
     * @param appId
     * @return
     */
    @Override
    public Object platformVerifyToken(String appId) {


        return null;
    }
}
